import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { getRouters, getNavs } from '@/api/menu'

router.beforeEach((to, from, next) => {
    const tokenStr = getToken();
    if (tokenStr) {
        if (store.state.permission.routes.length !== 0)
            next()
        else {
            store.commit("setRoutes", 1)
            console.log(store.state.permission.routes)
            const tmproute = {
                path: '/',
                name: 'home',
                component: () => import(`@/views/Home`),
                children: [
                    {
                        path: '/dashboard',
                        component: () => import(`@/views/DashBoard`)
                    }
                ]
            }
            getRouters().then(res => {
                for (let i = 0; i < res.length; i++) {
                    tmproute.children.push({
                        path: `/${res[i].path}`,
                        component: () => import(`@/views/${res[i].component}`)
                    })
                }
                console.log("2")
                console.log(router)
                router.addRoute(tmproute)
            })
            next({ ...to, replace: true })
        }
    }
    else {
        if (to.path !== '/login')
            next('/login')
        else
            next()
    }
})